package com.huali.servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码格式
        request.setCharacterEncoding("UTF-8");
        //设置响应编码格式
        response.setContentType("text/html;charset=UTF-8");
        //获取执行的方法名字
        String m = request.getParameter("m");
        //判断执行的方法不为空
        if (m != null && !"".equals(m)){
            try {
                //通过反射获取对应的方法
                Method method = this.getClass()
                        .getDeclaredMethod(m,
                                HttpServletRequest.class,
                                HttpServletResponse.class);

                Object value = method.invoke(this, request, response);

                response.getWriter().write(JSON.toJSONString(value));
            } catch (Exception e) {
                response.getWriter().write("找不到对应方法");
                e.printStackTrace();
            }
        }else {
            response.getWriter().write("找到对应方法");
        }
    }
}
